// pages/myinfo/myinfo.js
const {apiUrl} = getApp().globalData
import {UsersInfo, UsersSave, UsersSaveCompany, ShiChang, Country, Province} from "../../http/myinfo.js"

Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {},
        currentDate: new Date().getTime(),
        minDate: '',
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            } else if (type === 'month') {
                return `${value}月`;
            }
            return value;
        },
        radio: '1',
        show: false,
        radioItems: [
            {name: '先生', value: 1, checked: true},
            {name: '女士', value: 2, checked: false},
        ],
        hidden: false,
        birthday: '2016-09-01',
        array: ['美国', '中国', '巴西', '日本'],
        index: 0,
        region: ['', '', ''],
        customItem: '全部',
        works: ["互联网", "金融", "交通", "教育", "游戏", "政务警务", "工业", "其他"],
        workindex: 0,
        companys: ["组团参展商", "团员参展商", "直接参展商"],
        companyindex: 0,
        grades: ["主参展商", "合作参展商"],
        gradeindex: 0,
        areas: ["东北地区", "华北地区", "华中地区", "华东地区", "华南地区", "西北地区", "西南地区"],
        areaindex: 0,
        cansave: false,
        cansavecompany: false,
        api_token: null,
        showbtn: false,
        btnindex: 0,
        mobile00: '',
        mobile01: '',
        mobile02: '',
        mobile10: '',
        mobile11: '',
        mobile12: '',
        show0: true,
        show1: false,
        show2: false,
        show11: false,
        show22: false,
        show33: false,
        linkmanarry: [],
        shichanglist: [],
        sichangindex: 0,
        countrylist: [],
        countyindex: 0,
        provincelist: [],
        provinceindex: 0
    },
    _ShiChang() {
        var _ = this;
        ShiChang().then(res => {
            if (res.status == 1) {
                var shichanglist = res.data;
                shichanglist = Object.values(shichanglist);
                // console.log(shichanglist)
                _.setData({
                    shichanglist: shichanglist
                })
            }
        })
    },
    bindsichang(e) {
        // console.log(e)
        this.setData({
            sichangindex: e.detail.value
        })
    },
    _Country() {
        var _ = this;
        Country().then(res => {
            if (res.status == 1) {
                var countrylist = res.data;
                countrylist = Object.values(countrylist);
                // console.log(countrylist)
                _.setData({
                    countrylist: countrylist
                })
            }
        })
    },
    bindCountry(e) {
        this.setData({
            countyindex: e.detail.value
        })
    },
    _Province() {
        var _ = this;
        Province().then(res => {
            if (res.status == 1) {
                var provincelist = res.data;
                provincelist = Object.values(provincelist);
                // console.log(provincelist);
                _.setData({
                    provincelist: provincelist
                })
            }
        })
    },
    bindProvince(e) {
        this.setData({
            provinceindex: e.detail.value
        })
    },
    bindprovince(e) {
        this.setData({
            'userInfo.province': e.detail.value
        });
    },
    bindcity(e) {
        this.setData({
            'userInfo.city': e.detail.value
        });
    },
    // 获取用户/公司信息
    get_UsersInfo() {
        var _ = this;
        wx.getStorage({
            key: 'api_token',
            success: local => {
                UsersInfo(local.data).then(res => {
                    if (res.status == 1) {
                        _.setData({
                            userInfo: res.data
                        });
                        var sex = res.data.sex;
                        var work = res.data.work;
                        var label = res.data.label;
                        var country = res.data.country;
                        var province = res.data.province;
                        // 格式化固话格式
                        var mobile0 = res.data.mobile0;
                        var mobile1 = res.data.mobile1;
                        var mobile2 = res.data.mobile2;
                        var mobile3 = res.data.mobile3;
                        var name0 = res.data.name0;
                        var name1 = res.data.name1;
                        var name2 = res.data.name2;
                        var name3 = res.data.name3;
                        var phone0 = res.data.phone0;
                        var phone1 = res.data.phone1;
                        var phone2 = res.data.phone2;
                        var phone3 = res.data.phone3;

                        for (var i in _.data.radioItems) {
                            var checked = 'radioItems[' + i + '].checked'
                            if (sex == _.data.radioItems[i].value) {
                                _.setData({
                                    [checked]: true
                                })
                            } else {
                                _.setData({
                                    [checked]: false
                                })
                            }
                        }
                        for (var j in _.data.works) {
                            if (work == _.data.works[j]) {
                                _.setData({
                                    workindex: j
                                })
                            }
                        }
                        for (var k in _.data.companys) {
                            if (label == _.data.companys[k]) {
                                _.setData({
                                    companyindex: k
                                })
                            }
                        }
                        for (var x in _.data.countrylist) {
                            if (country == _.data.countrylist[x]) {
                                // console.log(x)
                                _.setData({
                                    countyindex: x
                                })
                            }
                        }
                        for (var y in _.data.provincelist) {
                            if (province == _.data.provincelist[y]) {
                                if (_.data.countyindex == 0) {
                                    _.setData({
                                        provinceindex: y
                                    })
                                } else {
                                    _.setData({
                                        'userInfo.province': province
                                    })
                                }
                            }
                        }
                        _.setData({
                            region: [res.data.uprovince, res.data.ucity, res.data.uarea],
                            'userInfo.uprovince': res.data.uprovince ? res.data.uprovince : '省',
                            'userInfo.ucity': res.data.ucity ? res.data.ucity : '市',
                            'userInfo.uarea': res.data.uarea ? res.data.uarea : '区',
                            'userInfo.mobile0': mobile0 ? mobile0.split('-') : '',
                            'userInfo.mobile1': mobile1 ? mobile1.split('-') : '',
                            'userInfo.mobile2': mobile2 ? mobile2.split('-') : '',
                            'userInfo.mobile3': mobile3 ? mobile3.split('-') : '',
                        });
                        var linkmanarry = [
                            {
                                name: name1,
                                phone: phone1,
                                mobile: _.data.userInfo.mobile1,
                                show: name1 != '' || phone1 != '' || _.data.userInfo.mobile1 != '',
                                error: false
                            },
                            {
                                name: name2,
                                phone: phone2,
                                mobile: _.data.userInfo.mobile2,
                                show: name2 != '' || phone2 != '' || _.data.userInfo.mobile2 != '',
                                error: false
                            },
                            {
                                name: name3,
                                phone: phone3,
                                mobile: _.data.userInfo.mobile3,
                                show: name3 != '' || phone3 != '' || _.data.userInfo.mobile3 != '',
                                error: false
                            },
                        ];
                        // console.log(linkmanarry);
                        var showbtn = linkmanarry.some((item) => {
                            return item.show == false
                        });
                        var btnindex = linkmanarry.findIndex((item) => {
                            return item.show == false
                        });
                        _.setData({
                            linkmanarry: linkmanarry,
                            showbtn: showbtn,
                            btnindex: btnindex
                        })
                    }
                })
            }
        });
    },
    // 保存观众信息
    _UsersSave() {
        var _ = this;
        if (_.data.userInfo.uprovince == '省' || _.data.userInfo.ucity == '市' || _.data.userInfo.uarea == '区') {
            return wx.showToast({
                title: '请选择所在地区',
                icon: 'none'
            })
        }
        _.setData({
            cansave: true
        })
        wx.getStorage({
            key: 'api_token',
            success: local => {
                UsersSave(
                    local.data,
                    _.data.userInfo.avatar,
                    _.data.userInfo.uaddress,
                    _.data.userInfo.position,
                    _.data.userInfo.uprovince,
                    _.data.userInfo.ucity,
                    _.data.userInfo.uarea,
                    _.data.works[_.data.workindex],
                ).then(res => {
                    // console.log(res)
                    _.setData({
                        cansave: false
                    });
                    if (res.status == 1) {
                        wx.showToast({
                            title: res.msg,
                            duration: 1000,
                        })
                    }
                })
            }
        });
    },
    // 头像上传
    imgUpload() {
        let that = this;
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (rlt) {
                // console.log(rlt)
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                let tempFilePaths = rlt.tempFilePaths; //图片的本地临时文件路径列表

                setTimeout(() => {
                    wx.showLoading({
                        title: '照片上传中...',
                        mask: true
                    });
                    wx.uploadFile({
                        url: apiUrl + '/api/users/avatar',
                        filePath: tempFilePaths[0],
                        header: {
                            'Accept': 'application/json' // 默认值
                        },
                        name: 'avatar',
                        formData: {
                            p: 't',
                            api_token: that.data.api_token,
                        },
                        success: (json) => {
                            // console.log(json)
                            wx.hideLoading()
                            if (json.errMsg == 'uploadFile:ok') {
                                let res = JSON.parse(json.data)
                                // console.log(res)
                                // res.data='/uploadfiles/member/20190826/201908261442298854.jpg'
                                if (res.status == 1) {
                                    that.setData({
                                        'userInfo.avatar': res.data
                                    })
                                } else {
                                    wx.showToast({
                                        icon: 'none',
                                        title: res.msg,
                                        duration: 1000,
                                    })
                                }
                            }
                        },
                        fail: (err) => {
                            wx.hideLoading()
                            that.showToast({
                                title: '照片上传失败，请重新上传',
                            })
                        },
                    })
                }, 500)
            }
        });
    },
    // 个人公司
    uaddress(e) {
        this.setData({
            'userInfo.uaddress': e.detail.value
        });
    },
    // 个人职位
    position(e) {
        this.setData({
            'userInfo.position': e.detail.value
        });
    },

    // onChange(event) {
    //     console.log(event)
    //     this.setData({
    //         radio: event.detail
    //     });
    // },
    // onClick(event) {
    //     const {name} = event.currentTarget.dataset;
    //     this.setData({
    //         radio: name
    //     });
    // },
    // onInput(event) {
    //     this.setData({
    //         currentDate: event.detail
    //     });
    // },
    // 保存公司信息
    _UsersSaveCompany() {
        var _ = this;
        if (_.data.linkmanarry[0].phone && !/^1\d{10}$/gi.test(_.data.linkmanarry[0].phone)) {
            return wx.showToast({
                title: '请输入正确的手机号',
                icon: 'none'
            })
        }
        var hasvalue = _.data.userInfo.mobile0.some(item => {
            return item
        });
        var hasvaluenull = _.data.userInfo.mobile0.some(item => {
            return item == ''
        });
        if (hasvalue) {
            if (hasvaluenull) {
                return wx.showToast({
                    title: '请输入正确的固定电话',
                    icon: 'none'
                })
            }
        }

        UsersSaveCompany(
            _.data.api_token,
            _.data.userInfo.company,
            _.data.userInfo.label,
            _.data.shichanglist[_.data.sichangindex],
            _.data.areas[_.data.areaindex],
            _.data.countrylist[_.data.countyindex],
            _.data.countyindex == 0 ? _.data.provincelist[_.data.provinceindex] : _.data.userInfo.province,
            _.data.userInfo.city,
            _.data.userInfo.address,
            _.data.companys[_.data.companyindex],
            _.data.grades[_.data.gradeindex],
            _.data.userInfo.name0,
            _.data.userInfo.mobile0 ? _.data.userInfo.mobile0.join('-') : '',
            _.data.userInfo.phone0,
            _.data.linkmanarry[0].name,
            _.data.linkmanarry[0].mobile.length ? _.data.linkmanarry[0].mobile.join('-') : '',
            _.data.linkmanarry[0].phone,
            _.data.linkmanarry[1].name,
            _.data.linkmanarry[1].mobile.length ? _.data.linkmanarry[1].mobile.join('-') : '',
            _.data.linkmanarry[1].phone,
            _.data.linkmanarry[2].name,
            _.data.linkmanarry[2].mobile.length ? _.data.linkmanarry[2].mobile.join('-') : '',
            _.data.linkmanarry[2].phone,
        ).then(res => {
            _.setData({
                cansavecompany: false
            })
            if (res.status == 1) {
                wx.showToast({
                    title: res.msg
                })
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'none'
                })
            }
        })
        _.setData({
            cansavecompany: true
        })
    },
    // 获取公司的值
    company(e) {
        this.setData({
            'userInfo.company': e.detail.value
        });
    },
    // 公司市场规划
    shichang(e) {
        this.setData({
            'userInfo.shichang': e.detail.value
        });
    },
    // 公司地址
    address(e) {
        this.setData({
            'userInfo.address': e.detail.value
        });
    },
    name(e) {
        let name = "linkmanarry[" + e.currentTarget.dataset.index + "].name"
        let value = e.detail.value
        this.setData({
            [name]: value
        })
        // console.log(this.data.linkmanarry)
    },
    phone(e) {
        let phone = "linkmanarry[" + e.currentTarget.dataset.index + "].phone";
        let error = "linkmanarry[" + e.currentTarget.dataset.index + "].error"
        let value = e.detail.value;
        let err = !/^1\d{10}$/gi.test(value);
        this.setData({
            [phone]: value,
            [error]: err
        })
        // console.log(this.data.linkmanarry)
    },
    // 删除联系人
    del(e) {
        let _ = this;
        this.initindex();
        let phone = "linkmanarry[" + e.currentTarget.dataset.index + "].phone";
        let name = "linkmanarry[" + e.currentTarget.dataset.index + "].name";
        let mobile = "linkmanarry[" + e.currentTarget.dataset.index + "].mobile";
        let show = "linkmanarry[" + e.currentTarget.dataset.index + "].show";
        let p = this.data.linkmanarry[e.currentTarget.dataset.index].phone;
        let n = this.data.linkmanarry[e.currentTarget.dataset.index].name;
        let m = this.data.linkmanarry[e.currentTarget.dataset.index].mobile;
        if (p || n || m) {
            wx.showModal({
                title: '提示',
                content: '是否删除联系人？',
                success(res) {
                    if (res.confirm) {
                        _.setData({
                            [phone]: '',
                            [name]: '',
                            [mobile]: [],
                            [show]: false,
                            showbtn: true
                        })
                    }
                }
            })
        } else {
            _.setData({
                [show]: false,
                showbtn: true
            })
        }
    },
    // 添加联系人
    addlink() {
        this.initindex();
        let show = "linkmanarry[" + this.data.btnindex + "].show";
        this.setData({
            [show]: true
        })
    },
    initindex() {
        // console.log(linkmanarry);
        let _ = this;
        var showbtn = this.data.linkmanarry.some((item) => {
            return item.show == false
        });
        var btnindex = this.data.linkmanarry.findIndex((item) => {
            return item.show == false
        });
        // console.log(btnindex)
        if (btnindex == -1) {
            _.setData({
                showbtn: showbtn,
            });
        } else {
            _.setData({
                showbtn: showbtn,
                btnindex: btnindex
            })
        }
    },

    // 联系人0
    _mobile00(e) {
        this.setData({
            'userInfo.mobile0[0]': e.detail.value
        });
    },
    _mobile01(e) {
        this.setData({
            'userInfo.mobile0[1]': e.detail.value
        });
    },
    _mobile02(e) {
        this.setData({
            'userInfo.mobile0[2]': e.detail.value
        });
    },
    // 联系人*
    _mobile0(e) {
        // console.log(e)
        let mobile = "linkmanarry[" + e.currentTarget.dataset.index + "].mobile[0]";
        this.setData({
            [mobile]: e.detail.value
        });
    },
    _mobile1(e) {
        let mobile1 = "linkmanarry[" + e.currentTarget.dataset.index + "].mobile[1]";
        this.setData({
            [mobile1]: e.detail.value
        });
    },
    _mobile2(e) {
        let mobile2 = "linkmanarry[" + e.currentTarget.dataset.index + "].mobile[2]";
        this.setData({
            [mobile2]: e.detail.value
        });
    },
    OnConfirm(e) {
        // console.log(e)
        this.setData({
            show: false
        });
    },
    onCancel() {
        this.setData({
            show: false
        });
    },
    onClose() {
        this.setData({
            show: false
        });
    },
    showborth() {
        this.setData({
            show: true
        });
    },
    // radioChange: function (e) {
    //     var checked = e.detail.value
    //     var changed = {}
    //     for (var i = 0; i < this.data.radioItems.length; i++) {
    //         if (checked.indexOf(this.data.radioItems[i].name) !== -1) {
    //             changed['radioItems[' + i + '].checked'] = true
    //         } else {
    //             changed['radioItems[' + i + '].checked'] = false
    //         }
    //     }
    //     this.setData(changed)
    // },
    bindDateChange: function (e) {
        // console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            birthday: e.detail.value
        })
    },
    // 改变行业类型
    bindPickerChange: function (e) {
        // console.log('picker发送选择改变，携带值为', e.detail.value)
        this.setData({
            workindex: e.detail.value
        })
    },
    bindCompanyChange(e) {
        this.setData({
            companyindex: e.detail.value
        })
    },
    bindAreaChange(e) {
        this.setData({
            areaindex: e.detail.value
        })
    },
    bindGradeChange(e) {
        this.setData({
            gradeindex: e.detail.value
        })
    },
    // 改变城市选择
    bindRegionChange: function (e) {
        // console.log('picker发送选择改变，携带值为', e.detail.province)
        this.setData({
            'userInfo.uprovince': e.detail.province,
            'userInfo.ucity': e.detail.city,
            'userInfo.uarea': e.detail.county,
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var _ = this;
        this._ShiChang();
        this._Country();
        this._Province();
        this.get_UsersInfo();
        // api_token
        wx.getStorage({
            key: 'api_token',
            success(res) {
                _.setData({
                    api_token: res.data
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})